package xin.nick.roc.consumer.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * @author Nick
 * @date 2021/7/4
 * @description 客户端处理类
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext context;

    private String requestMsg;

    private String responseMsg;

    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

    /**
     * 通道就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.context = ctx;
    }

    /**
     * 通道读取就绪事件
     * @param channelHandlerContext
     * @param msg
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        responseMsg = msg;
        // 唤醒等待的线程
        notify();
    }


    /**
     * 发送消息到服务器
     * @return
     * @throws Exception
     */
    @Override
    public synchronized Object call() throws Exception {
        // 消息发送
        context.writeAndFlush(requestMsg);
        // 线程等待
        wait();
        return responseMsg;
    }
}
